var express = require('express');
var router = express.Router();
let { userModel, authority, role } = require('../../modules/model')
let jwt = require('jsonwebtoken')
let md5 = require('md5-node');
let multiparty = require('multiparty')
let ws = require('ws')

/*账户登录验证 */
router.post('/login', async (req, res) => {
  let { username, password } = req.body
  console.log(username,password);
  let data = await userModel.find({ username:username })
  // console.log(data[0].password);

  
  if (data.length <= 0) {
    console.log(data);
    return res.send({
      code: 404,
      msg: '用户不存在'
    })
  }
  if (password != data[0].password) {
   
    return res.send({
      code: 401,
      msg: '密码错误'
    })
  }
  let userInfo = {
    username,
    
  }
  let accessToken = jwt.sign(userInfo, 'abcdefg', { expiresIn: '3s' })
  let refreshToken = jwt.sign(userInfo, 'abcdefg', { expiresIn: '7d' })
  // console.log(data, 3333);
  return res.send({
    code: 200,
    data
     
  })
});
router.get("/render", async (req, res) => {
  //登录之后获取的角色ID
  let id = req.query.id;
  // console.log(id,'获取角色ID');
  //根据角色ID查找相对应的角色
  let obj = await role.findOne({ _id:id });
  // console.log(obj,"根据角色DI查找对应的角色");
  //获取角色中所有权限(数组)q
  let ids = obj.qid;
  // console.log(ids,"输入角色的权限");
  
  //根据双层循环查找角色权限的所有权限信息
  let authoritys = await authority.find().lean();
  let authoritylist = [];
  ids.forEach((item) => {
    authoritys.forEach((items) => {
      if (String(item) == String(items._id)) {
        authoritylist.push(items);
      }
    });
  });

  //将权限ID和权限信息一一对应，方便在前端使用
  let authorityobj = {};
  authoritylist.forEach((item) => {
    authorityobj[item._id] = item;
  });
  //将权限信息按父子关系排序
  let list = [];
  let top = []; //一级菜单
  let left = []; //二级菜单
  authoritylist.forEach((item) => {
    if (!item.pid) {
      list.push(item);
      top.push(item);
    } else {
      if (!authorityobj[item["pid"]]["children"]) {
        authorityobj[item["pid"]]["children"] = [];
      }
      authorityobj[item["pid"]]["children"].push(item);
    }
  });

  res.send({
    code: 200,
    data: list,
    top,
    left,
  });
});


module.exports = router;

